package com.gxuwz.business.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.gxuwz.business.entity.Medicine;
import com.gxuwz.business.entity.RecMed;
import com.gxuwz.business.entity.Recipe;
import com.gxuwz.business.entity.Student;
import com.gxuwz.business.entity.SysUser;
import com.gxuwz.business.entity.Treat;
import com.gxuwz.business.service.IFeeService;
import com.gxuwz.business.service.IMedicineService;
import com.gxuwz.business.service.IRecMedService;
import com.gxuwz.business.service.IRecipeService;
import com.gxuwz.business.service.IStudentService;
import com.gxuwz.business.service.ITreatService;
import com.gxuwz.util.Pager;
import com.gxuwz.util.UidUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

import net.sf.json.JSONObject;

public class RecipeAction extends BaseAction implements Preparable,ModelDriven<Recipe>{

	private static final long serialVersionUID = 1967497289683795973L;
	
	private static final String RECIPE_LIST = "/WEB-INF/page/recipe/recipe_list.jsp";
	private static final String RECIPE_ADD = "/WEB-INF/page/recipe/recipe_add.jsp";
	private static final String MEDFEE_LIST = "/WEB-INF/page/medicine/medFee_list.jsp";
	
	@Autowired
	private IRecipeService recipeService;
	@Autowired
	private ITreatService treatService;
	@Autowired
	private IStudentService studentService;
	@Autowired
	private IMedicineService medicineService;
	@Autowired
	private IRecMedService recMedService;
	@Autowired
	private IFeeService feeService;
	
	private Student student = new Student();
	private Recipe recipe;
	private Treat treat = new Treat();
	private List<Recipe> recipeLists;//一诊疗单对应的处方单数据
	private String medicineDesc;//接收药品及数量字符串
	private String[] medicineCount;//存放分割后的药品及数量信息
	private String[] medicineCounts;//存放分割后的药品及数量信息
	private Pager<Recipe> recipeList;//存放分页数据
	private Pager<Treat> treatList;//存放分页数据
	private Map<String, String> recMedList = new HashMap<String, String>();//存放每条处方单号对应的药品信息
	private Map<String, List<String>> treIdRecIdList = new HashMap<String, List<String>>();//诊编对应处编集合
	private Map<String, Double> treIdMedFee = new HashMap<String, Double>();//诊编对应的全部药品费用
	private Map<String, Double> recIdMedFee = new HashMap<String, Double>();//处编对应的全部药品费用
	private JSONObject recMedListJson;//存放每条处方单号对应的药品信息
	private JSONObject treIdRecIdListJson;//诊编对应处编集合
	private JSONObject treIdMedFeeJson;//诊编对应的全部药品费用
	private JSONObject recIdMedFeeJson;//处编对应的全部药品费用
	private List<String> treatIdList;//诊编集合
	private List<String> recipeIdList;//处编集合
	private List<String> medIdList;//药编集合

	/**
	 * 构造药品费用记录
	 */
	public String openFeeOfMedList(){
		//获取所有已开处方的诊编集合
		treatIdList = treatService.getAllIdIsRecipe();
		//构造 诊编---处编集 哈希表
		for(String treatId: treatIdList){
			recipeIdList = recipeService.getByTreatId(treatId);
			treIdRecIdList.put(treatId, recipeIdList);
			//初始化诊编对应全部处方单药品总价
			Double totleFee = 0.0;
			//初始化处编对应药品总价
			Double medPrices = 0.0;
			//构造 处编---药品信息(药名/单价/数量/价格)
			for(String recipeId: recipeIdList){
				//根据处方编号查询对应药品编号
				medIdList = recMedService.getAllMedId(recipeId);
				//初始化药品信息集合
				List<String> medList = new ArrayList<String>();
				//初始化药名
				String medName = "";
				//初始化单价
				Double medPrice = 0.0;
				//循环药编集合
				for(String medId : medIdList){
					//根据药编查询药名
					medName = medicineService.getMedName(medId);
					medPrice = medicineService.getMedPrice(medId);
					//根据处编和药编查询药品数量及总价
					RecMed recMed = recMedService.findByRecMedId(recipeId, medId);
					//累计价格
					Double newPrice = medPrice*recMed.getMedicineCount();
					medPrices = medPrices+newPrice;
					medList.add(medName+" "+medPrice.toString()+"元 "+recMed.getMedicineCount()+"盒 "+recMed.getMedicineFee()+"元");
				}
				//处编对应药品总价
				recIdMedFee.put(recipeId, medPrices);
				//将处编与药品信息集合对应
				recMedList.put(recipeId, medList.toString());
				//构造 诊编---药品总价
				totleFee += medPrices;
				treIdMedFee.put(treatId, totleFee);
			}

		}
		treIdMedFeeJson = JSONObject.fromObject(treIdMedFee);
		recIdMedFeeJson = JSONObject.fromObject(recIdMedFee);
		treIdRecIdListJson = JSONObject.fromObject(treIdRecIdList);
		recMedListJson = JSONObject.fromObject(recMedList);
		forwardView = MEDFEE_LIST;
		return SUCCESS;
	}
	
	
	/**
	 * 打开添加页面
	 * @return
	 */
	public String openAdd(){
		//根据对应诊疗表
		treat = treatService.findById(treat);
		//查询挂号表
		student.setRegId(treat.getRegId());
		student = studentService.findById(student);
		forwardView = RECIPE_ADD;
		return SUCCESS;
	}
	
	/**
	 * 添加处方单
	 */
	@SuppressWarnings("deprecation")
	public String add(){
		//分割成'药品编号a数量'的格式
		medicineCount = medicineDesc.split("b");
		//随机生成处方单号
		recipe.setRecipeId(UidUtils.UIDD());
		recipe.setRecipeDate(new Date());
		recipe.setStatus(0);
		//设置处方单完成与否状态
		recipe.setState(0);
		//更改诊疗单治疗次数以及诊疗状态
		treat.setTreatId(recipe.getTreatId());
		treat = treatService.findById(treat);
		treat.setTreatCount(treat.getTreatCount()+1);
		switch(treat.getState()){
		case 0:
			treat.setState(1);break;
		case 1:
			treat.setState(1);break;
		case 2:
			treat.setState(1);break;
		}
		treatService.updateCountState(treat);
		//保存处方单
		isSucceed = recipeService.add(recipe);
		if(isSucceed){
			for(String med: medicineCount){
				//继续分割成 ['药品','数量']的数组格式
				medicineCounts = med.split("a");
				//通过药品编号查询价格
				Medicine medicine = new Medicine();
				medicine.setMedId(medicineCounts[0]);
				medicine = medicineService.findById(medicine);
				//构造RecMed对象 (处方药品)
				RecMed recMed = new RecMed(recipe.getRecipeId(), medicineCounts[0], Integer.valueOf(medicineCounts[1]), 
						Integer.valueOf(medicineCounts[1])*medicine.getMedPrice());
				boolean isSucceeds = recMedService.add(recMed);
				if(!isSucceeds){
					System.err.println("插入 处方-药品 错误");
				}
			}
		}
		jsonString = jsonToString(isSucceed);
		return "JsonString";
	}
	
	/**
	 * 打开处方列表 (构造 处方编号  : 药品信息)
	 */
	public String recipeList(){
		//查询所有处方编号
		recipeIdList = recipeService.getAllId();
		//初始化药名
		String medName = "";
		//循环处方编号集合
		for(String recipeId : recipeIdList){
			//根据处方编号查询对应药品编号
			medIdList = recMedService.getAllMedId(recipeId);
			//初始化药名集合
			List<String> medNameList = new ArrayList<String>();
			//循环药编集合
			for(String medId : medIdList){
				//根据药编查询药名
				medName = medicineService.getMedName(medId);
				medNameList.add(medName);
			}
			//将处编与药名集合对应
			recMedList.put(recipeId, medNameList.toString());
		}
		
		JsonData = JSONObject.fromObject(recMedList);
		forwardView = RECIPE_LIST;
		return SUCCESS;
	}
	
	/**
	 * 分页查询
	 */
	public String getByPager(){
		recipeList = recipeService.getByPager(page, limit);
		JsonData = JSONObject.fromObject(recipeList);
		return "JsonObject";
	}
	
	/**
	 * 分页查询已开处方的诊疗列表
	 */
	public String getByPagerRec(){
		treatList = treatService.getByPagerRec(page, limit);
		System.out.println(treatList);
		JsonData = JSONObject.fromObject(treatList);
		return "JsonObject";
	}
	
	
	/**
	 * 处方单完成
	 */
	@SuppressWarnings("deprecation")
	public String recipeSucceed(){
		try {
			recipe = recipeService.findById(recipe.getRecipeId());
			treat = treatService.findById(treat);
			student.setRegId(treat.getRegId());
			student = studentService.findById(student);
			//处方完成并保存
			recipe.setState(1);
			recipeService.update(recipe);
			//查询对应诊疗单所包含的所有处方单信息
			recipeLists = recipeService.getAllByTreatId(recipe.getTreatId());
			//处方单状态集合
			List<Integer> states = new ArrayList<Integer>();
			//获取诊疗单对应的所有处方单状态
			for(Recipe recipes: recipeLists){
				states.add(recipes.getState());
			}
			//如果诊疗单包含的处方单有一单未开始诊断的话，诊疗单就未完成
			if(states.contains(0)){
				//未完成
				treat.setState(1);
			 
			//相应的处方单全部有结果的话(成功或失败)
		    //又因本次操作为处方完成操作，可视为最后一次的处方诊断，按理说病情已暂时安稳，因此视为诊疗完成
			}else{
				//诊疗单完成
				treat.setState(3);
				//处方完成
				student.setState(3);
				//获取用户
				SysUser user = (SysUser)getSession().getAttribute("user");
				//恭喜~进入缴费阶段
				feeService.add(student, treat, user);
				System.out.println("进入缴费阶段");
			}
			studentService.updates(student);
			treatService.update(treat);
		} catch (Exception e) {
			e.printStackTrace();
			jsonString = jsonToString(false);
		}
		jsonString = jsonToString(true);
		return "JsonString";
	}
	
	/**
	 * 处方单失效
	 */
	@SuppressWarnings("deprecation")
	public String recipeFail(){
		try {
			recipe = recipeService.findById(recipe.getRecipeId());
			treat = treatService.findById(treat);
			student.setRegId(treat.getRegId());
			student = studentService.findById(student);
			//处方完成并保存
			recipe.setState(2);
			recipeService.update(recipe);
			//查询对应诊疗单所包含的所有处方单信息
			recipeLists = recipeService.getAllByTreatId(recipe.getTreatId());
			//处方单状态集合
			List<Integer> states = new ArrayList<Integer>();
			//获取诊疗单对应的所有处方单状态
			for(Recipe recipes: recipeLists){
				states.add(recipes.getState());
			}
			//如果诊疗单包含的处方单有一单未开始诊断的话，诊疗单就未完成
			if(states.contains(0)){
				//未完成
				treat.setState(1);
			}
			//相应的处方单全部有结果的话(成功或失败)
		    //又因本次操作为处方失败操作，可视为最后一次的处方诊断，按理说病情还未安稳，因此视为诊疗失败
			else{
				//诊疗失败
				treat.setState(2);
				//处方失败
				student.setState(2);
			}
			studentService.updates(student);
			treatService.update(treat);
		} catch (Exception e) {
			e.printStackTrace();
			jsonString = jsonToString(false);
		}
		jsonString = jsonToString(true);
		return "JsonString";
	}
	
	
	
	@Override
	public Recipe getModel() {
		return recipe;
	}

	@Override
	public void prepare() throws Exception {
		if(null == recipe){
			recipe = new Recipe();
		}
	}

	public Treat getTreat() {
		return treat;
	}

	public void setTreat(Treat treat) {
		this.treat = treat;
	}

	public Student getStudent() {
		return student;
	}

	public void setStudent(Student student) {
		this.student = student;
	}

	public String getMedicineDesc() {
		return medicineDesc;
	}

	public void setMedicineDesc(String medicineDesc) {
		this.medicineDesc = medicineDesc;
	}

	public Map<String, String> getRecMedList() {
		return recMedList;
	}

	public void setRecMedList(Map<String, String> recMedList) {
		this.recMedList = recMedList;
	}
	
	public Map<String, List<String>> getTreIdRecIdList() {
		return treIdRecIdList;
	}

	public void setTreIdRecIdList(Map<String, List<String>> treIdRecIdList) {
		this.treIdRecIdList = treIdRecIdList;
	}


	public JSONObject getRecMedListJson() {
		return recMedListJson;
	}


	public void setRecMedListJson(JSONObject recMedListJson) {
		this.recMedListJson = recMedListJson;
	}


	public JSONObject getTreIdRecIdListJson() {
		return treIdRecIdListJson;
	}


	public void setTreIdRecIdListJson(JSONObject treIdRecIdListJson) {
		this.treIdRecIdListJson = treIdRecIdListJson;
	}


	public JSONObject getTreIdMedFeeJson() {
		return treIdMedFeeJson;
	}


	public void setTreIdMedFeeJson(JSONObject treIdMedFeeJson) {
		this.treIdMedFeeJson = treIdMedFeeJson;
	}


	public JSONObject getRecIdMedFeeJson() {
		return recIdMedFeeJson;
	}


	public void setRecIdMedFeeJson(JSONObject recIdMedFeeJson) {
		this.recIdMedFeeJson = recIdMedFeeJson;
	}
	
	
	

}
